import os
import sys
from threading import Thread

import requests

from PySide2.QtWidgets import QApplication
from PySide2.QtUiTools import QUiLoader
from PySide2.QtCore import QFile, QObject, Signal


# 自定义信号源
class Mysignals(QObject):
    response_success = Signal(requests.Response)


# noinspection PyUnresolvedReferences
class Http1220:
    def __init__(self):
        self.request = requests
        ui_path = self.resource_path('http1220.ui')
        file = QFile(ui_path)  # 文件所在路径
        file.open(QFile.ReadOnly)
        self.ui = QUiLoader().load(file)
        self.ui.button_request.clicked.connect(self.start_request_handle)
        self.ui.button_stop_request.clicked.connect(self.stop_request_handle)
        self.ms = Mysignals()
        self.ms.response_success.connect(self.update_ui)
        self.request_t = None

    def update_ui(self, r):
        self.ui.textbrowser_response.setText(r.text)

    def stop_request_handle(self):
        self.ui.button_request.setEnabled(True)
        self.ui.repaint()

    def start_request_handle(self):
        # 地址
        ui = self.ui
        addr = ui.lineedit_addr.text().strip()
        method = ui.combobox_rmethod.currentText()
        table_rargs = ui.table_rargs
        table_rheaders = ui.table_rheaders
        # 遍历列表并生成字典
        table_rheaders_len = table_rheaders.rowCount()
        table_rargs_len = table_rargs.rowCount()
        # 请求参数
        rargs = {}
        # 请求头参数
        rheaders = {}
        for i in range(table_rargs_len):
            key = table_rargs.item(i, 0).text()
            value = table_rargs.item(i, 1).text()
            rargs.__setitem__(key, value)

        for i in range(table_rheaders_len):
            key = table_rheaders.item(i, 0).text()
            value = table_rheaders.item(i, 1).text()
            rheaders.__setitem__(key, value)

        # 启动一个线程发起请求
        def request():
            r = requests.get(addr)
            r.encoding = 'utf8'
            if r.status_code == 200:
                self.ms.response_success.emit(r)
                self.ui.button_request.setEnabled(False)

        self.request_t = Thread(target=request)
        self.request_t.start()

    @staticmethod
    def resource_path(relative_path):
        if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'):
            base_path = _MEIPASS
        else:
            base_path = os.path.abspath(".")
        return os.path.join(base_path, relative_path)


if __name__ == '__main__':
    app = QApplication([])
    http = Http1220()
    http.ui.show()
    app.exec_()
